package com.company.cloud.product.modules.mgr.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.modules.api.response.Artist;
import com.company.cloud.art.modules.api.service.ArtArtistRemoteService;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.company.modules.api.response.CompanySimple;
import com.company.cloud.company.modules.api.service.CompanyRemoteService;
import com.company.cloud.product.constant.ProductCheckStateEnum;
import com.company.cloud.product.constant.ProductErrorEnum;
import com.company.cloud.product.modules.api.response.Product;
import com.company.cloud.product.modules.api.response.ProductCategoryModel;
import com.company.cloud.product.modules.app.service.ProductStockQueryService;
import com.company.cloud.product.modules.base.entity.*;
import com.company.cloud.product.modules.base.service.*;
import com.company.cloud.product.modules.bus.producer.ProductProducer;
import com.company.cloud.product.modules.cache.service.ProductConfigCacheService;
import com.company.cloud.product.modules.cache.service.ProductDisProfitCacheService;
import com.company.cloud.product.modules.cache.service.ProductInfoCacheService;
import com.company.cloud.product.modules.cache.utils.ProductCacheConvertUtils;
import com.company.cloud.product.modules.mgr.controller.req.*;
import com.company.cloud.product.modules.mgr.controller.resp.SpecificationModel;
import com.company.cloud.product.modules.mgr.mapper.ArtistUpdateMapper;
import com.company.cloud.product.modules.mgr.service.ProductMgrService;
import com.company.common.server.config.cloud.ProjectConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;


/**
 * 商品信息管理
 */
@Authc
@RestController
@RequestMapping("/mgr/prd/product")
@Api(tags = "Product_Mgr_商品信息管理")
public class ProductMgrController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private ProductMgrService productMgrService;

    @Autowired
    private ProductConfigCacheService productConfigCacheService;

    @Autowired
    private ProductInfoCacheService productInfoCacheService;

    @Autowired
    private ProductStockInfoService productStockInfoService;

    @Autowired
    private SpecificationInfoService specificationInfoService;

    @Autowired
    private ProductDisProfitCacheService productDisProfitCacheService;

    @Autowired
    private ProductStockQueryService productStockQueryService;

    @Autowired
    private ProjectConfig projectConfig;

    @Autowired
    private ProductProducer productProducer;

    @Autowired
    private ArtArtistRemoteService artArtistRemoteService;

    @Autowired
    private CompanyRemoteService companyRemoteService;

    @Autowired
    private ArtistUpdateMapper artistUpdateMapper;

    @Autowired
    private CategoryInfoService categoryInfoService;


//	UPDATE prd_product_info a ,com_company_info b set a.biz_value20= b.name where a.company_no= b.company_no


    private BaseResult _query(ProductInfoQuery4PageParam params, LoginSimpleUserInfo userInfo) {
        String tag = null;
        if (StringUtils.hasText(params.getTagId())) {
            tag = StrUtil.format(",{},", params.getTagId());
        }
        IPage<ProductInfo> page = productInfoService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<ProductInfo>()
                        .eq("rows_state", EnabledEnum.ENABLED.getCode())
                        .eq(CheckUtils.hasText(params.getCompanyNo()), "company_no", params.getCompanyNo())
//			.eq(CheckUtils.hasText(params.getIsSelf()),"company_no", userInfo.getCompanyNo())
//			.eq(CheckUtils.hasText(params.getCompanyNo()), "company_no", params.getCompanyNo())
                        .eq(CheckUtils.hasText(params.getMainCompanyNo()), "main_company_no", params.getMainCompanyNo())
                        .eq(CheckUtils.hasText(params.getProductNo()), "product_no", params.getProductNo())
                        .eq(CheckUtils.hasText(params.getMainProductNo()), "main_product_no", params.getMainProductNo())
                        .apply(CheckUtils.hasText(params.getIsRel()), "product_no=main_product_no")
                        .eq(CheckUtils.hasText(params.getIsAgent()), "is_agent", params.getIsAgent())
                        .eq(CheckUtils.hasText(params.getIsMarketable()), "is_marketable", params.getIsMarketable())
                        .like(StringUtils.hasText(tag), "tag_values", tag)
                        .eq(CheckUtils.hasInt(params.getCategoryId()), "category_id", params.getCategoryId())
                        .eq(CheckUtils.hasInt(params.getBrandId()), "brand_id", params.getBrandId())
                        .eq(CheckUtils.hasText(params.getType()), "type", params.getType())
                        .eq(CheckUtils.hasText(params.getUnit()), "unit", params.getUnit())
                        .like(CheckUtils.hasText(params.getName()), "name", params.getName())
                        .like(CheckUtils.hasText(params.getCaption()), "caption", params.getCaption())
                        .like(CheckUtils.hasText(params.getKeyword()), "keyword", params.getKeyword())
//			.like(CheckUtils.hasInt(params.getTagId()), "parameter_values",params.getTagId()==null?"": ","+params.getTagId().toString()+",")
                        .eq(CheckUtils.hasText(params.getBizValue1()), "biz_value1", params.getBizValue1())
                        .eq(CheckUtils.hasText(params.getBizValue2()), "biz_value2", params.getBizValue2())
                        .eq(CheckUtils.hasText(params.getBizValue3()), "biz_value3", params.getBizValue3())
                        .eq(CheckUtils.hasText(params.getBizValue4()), "biz_value4", params.getBizValue4())
                        .eq(CheckUtils.hasText(params.getBizValue5()), "biz_value5", params.getBizValue5())
                        .eq(CheckUtils.hasText(params.getBizValue6()), "biz_value6", params.getBizValue6())

                        .eq(CheckUtils.hasText(params.getBizValue7()), "biz_value7", params.getBizValue7())
                        .eq(CheckUtils.hasText(params.getBizValue8()), "biz_value8", params.getBizValue8())
                        .eq(CheckUtils.hasText(params.getBizValue9()), "biz_value9", params.getBizValue9())
                        .eq(CheckUtils.hasText(params.getBizValue11()), "biz_value11", params.getBizValue11())

                        .like(CheckUtils.hasText(params.getBizValue19()), "biz_value19", params.getBizValue19())
                        .like(CheckUtils.hasText(params.getBizValue20()), "biz_value20", params.getBizValue20())

                        .eq(CheckUtils.hasInt(params.getStockNum()), "stock_num", params.getStockNum())
                        .eq(StrUtil.isNotEmpty(params.getState()), "state", params.getState())
                        .orderByDesc("cdt")
        );
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }
        Set<String> companyNos = new HashSet<String>();
        Set<String> productNos = new HashSet<String>();
        Set<String> artistNos = new HashSet<String>();
        page.getRecords().forEach(item -> {
            companyNos.add(item.getMainCompanyNo());
            productNos.add(item.getMainProductNo());
            if (StrUtil.isNotEmpty(item.getBizValue4())) {
                Set<String> artistNos2 = StrSplitUtils.parse2set(item.getBizValue4(), String.class);
                artistNos.addAll(artistNos2);
            }
        });

        Map<String, ProductStockInfo> stockMap = productStockQueryService.getPrdStockByPrd(productNos);

        List<SkuInfo> skuList = null;
        if (YNEnum.YES.getCode().equals(params.getIsSku())) {
            skuList = skuInfoService.list(new QueryWrapper<SkuInfo>().in("product_no", productNos));
        }
        List<SkuInfo> skus = skuList;

        Map<String, Map<Integer, ProductCategoryModel>> categoryMap = productConfigCacheService.getProductCategorysMapByCache(companyNos);


        BaseClientResult<Map<String, CompanySimple>> companySimpleRest = companyRemoteService.getCompanyMapSimple(companyNos);
        Map<String, CompanySimple> companySimpleMap = BaseClientResult.getResultData(companySimpleRest, new HashMap<String, CompanySimple>());

        //作家
        BaseClientResult<Map<String, Artist>> artistResp = artArtistRemoteService.artistInfoMap(artistNos);
        Map<String, Artist> artistData = BaseClientResult.getResultData(artistResp, new HashMap<String, Artist>());


        IPage<Product> data = page.convert(new Function<ProductInfo, Product>() {

            @Override
            public Product apply(ProductInfo entity) {
                Map<Integer, ProductCategoryModel> map = null;
                if (categoryMap != null) {
                    map = categoryMap.get(entity.getCompanyNo());
                }
                Product product = ProductCacheConvertUtils.convertProduct(entity, map, skus);
                ProductStockInfo stock = stockMap.get(product.getMainProductNo());
                if (stock != null) {
                    product.setStockNum(stock.getNum());
                    product.setFreezeNum(stock.getFreezeNum());
                }

                if (companySimpleMap != null) {
                    CompanySimple company = companySimpleMap.get(entity.getCompanyNo());
                    if (company != null) {
                        product.setCompanyName(company.getName());
                    }
                }

                if (StrUtil.isNotEmpty(entity.getBizValue4())) {
                    Set<String> artistNos3 = StrSplitUtils.parse2set(entity.getBizValue4(), String.class);
                    if (artistNos3.size() > 0) {
                        for (String ano : artistNos3) {
                            Artist artist = artistData.get(ano);
                            if (artist != null) {
                                product.addArtist(ProductCacheConvertUtils.getArtist(artist));
                                product.addArtistName(artist.getName());
                            }
                        }
                    }
                }

                if (StrUtil.isNotEmpty(entity.getTreePath())) {
                    Set<String> treePath = StrSplitUtils.parse2set(entity.getTreePath(), String.class);
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String tree : treePath) {
                        final CategoryInfo categoryInfo = categoryInfoService.getBaseMapper().selectById(tree);
                        if (categoryInfo != null) {
                            stringBuffer.append(categoryInfo.getName()).append(",");

                        }
                    }
                    if (stringBuffer.length() > 0) {
                        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                        product.setTreePath(String.valueOf(stringBuffer));
                    } else {
                        product.setTreePath("");
                    }

                }
                return product;
            }
        });
        return BaseResult.ok(data);

    }

    @PostMapping("/query")
    @ApiOperation(value = "商品信息查询", response = Product.class)
    public BaseResult query(@RequestBody ProductInfoQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
//		if(!projectConfig.isPlatformPattern()) {
//			params.setCompanyNo(userInfo.getCompanyNo());
//		}
        if (!"PTC".equals(userInfo.getCompanyNo())) {
            params.setCompanyNo(userInfo.getCompanyNo());
        }
        return _query(params, userInfo);
    }

    @PostMapping("/queryPlatform")
    @ApiOperation(value = "平台发布的商品信息查询", response = Product.class)
    public BaseResult queryPlatform(@RequestBody ProductInfoQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        if (!projectConfig.isPlatformPattern()) {
            params.setCompanyNo(userInfo.getCompanyNo());
        }
        params.setIsAgent(YNEnum.YES.getCode());
        params.setIsMarketable(YNEnum.YES.getCode());
        return _query(params, userInfo);
    }

    @GetMapping("/get")
    @ApiOperation(value = "商品信息详情查询", response = Product.class)
    public BaseResult get(@RequestParam("id") String id) {
        Product product = productInfoCacheService.getProductByNoByDB(id);
        //分销参数
//		ProductDisProfitModel productDis=productDisProfitCacheService.getProductDisProfitByDB(id);
//		result.setDisProfitConfig(productDis);

        //库存
        Map<String, ProductStockInfo> stockMap = productStockQueryService.getSkuStockByPrdNo(product.getMainProductNo());

        if (!CollectionUtils.isEmpty(product.getSkuItems())) {
            product.getSkuItems().forEach(sku -> {
                ProductStockInfo skuStock = stockMap.get(sku.getMainSkuNo());
                if (skuStock != null) {
                    sku.setStockNum(skuStock.getNum());
                    sku.setFreezeNum(skuStock.getFreezeNum());
                    if (sku.getMainSkuNo().equals(product.getMainProductNo())) {
                        product.setStockNum(skuStock.getNum());
                        product.setFreezeNum(skuStock.getFreezeNum());
                    }
                }
            });
        }

        //作家
        if (StrUtil.isNotEmpty(product.getBizValue4())) {
            Set<String> artistNos = StrSplitUtils.parse2set(product.getBizValue4(), String.class);
            if (artistNos.size() > 0) {
                BaseClientResult<List<Artist>> artistResp = artArtistRemoteService.artistInfoList(artistNos);
                List<Artist> artistData = BaseClientResult.getResultData(artistResp, new ArrayList<Artist>());
                artistData.forEach(item -> {
                    product.addArtist(ProductCacheConvertUtils.getArtist(item));
                    product.addArtistName(item.getName());
                });
            }
        }

        //公司信息
        BaseClientResult<CompanySimple> companyResp = companyRemoteService.getCompanySimple(product.getCompanyNo());
        if (CheckUtils.hasClientResult(companyResp)) {
            product.setCompany(companyResp.getData());
        }

        return BaseResult.ok(product);
    }

    @PostMapping("/save")
    @ApiOperation(value = "商品信息新增", response = BaseResult.class)
    @StaffLogc(title = "商品信息新增", action = "商品信息新增", actionAdo = "商品信息")
    public BaseResult save(@RequestBody ProductInfoSaveParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        if ("PTC".equals(userInfo.getCompanyNo())) {
            if (StrUtil.isEmpty(params.getCompanyNo())) {
                params.setCompanyNo(userInfo.getCompanyNo());
            }
        } else {
            params.setCompanyNo(userInfo.getCompanyNo());
        }
        params.setIsMarketable(YNEnum.NO.getCode());
        ProductInfo product = productMgrService.save(params, userInfo);
        productProducer.addPrd(product);
        this.updateArtist(product.getBizValue4());

        /**
         * 增加商品信息时，同时修改（无图的）分类图
         */
        Integer categoryId = product.getCategoryId();
        CategoryInfo category = categoryInfoService.getById(categoryId);
        if (category != null && org.apache.commons.lang3.StringUtils.isEmpty(category.getImg())) {
            category.setImg(product.getImage());
            categoryInfoService.updateById(category);
        }
        productConfigCacheService.removeProductCategoryByCache(params.getCompanyNo());
        return BaseResult.ok();
    }

    @PostMapping("/update")
    @ApiOperation(value = "商品信息修改", response = BaseResult.class)
    @StaffLogc(title = "商品信息修改", action = "商品信息修改", actionAdo = "商品信息")
    public BaseResult update(@RequestBody ProductInfoUpdateParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ProductInfo productOld = productInfoService.getById(params.getProductNo());
        ProductInfo product = productMgrService.update(params, userInfo);
        productProducer.editPrd(product);
        this.updateArtist(productOld.getBizValue4());
        this.updateArtist(product.getBizValue4());

        /**
         * 修改商品信息时，同时修改（无图的）分类图
         */
        Integer categoryId = product.getCategoryId();
        CategoryInfo category = categoryInfoService.getById(categoryId);
        if (category != null && org.apache.commons.lang3.StringUtils.isEmpty(category.getImg())) {
            category.setImg(product.getImage());
            categoryInfoService.updateById(category);
        }
        productConfigCacheService.removeProductCategoryByCache(params.getCompanyNo());

        return BaseResult.ok();
    }


    private void updateArtist(String bizValue4) {
        if (StrUtil.isEmpty(bizValue4)) {
            return;
        }
        Set<String> artistNos = StrSplitUtils.parse2set(bizValue4, String.class);
        if (CollUtil.isEmpty(artistNos)) {
            return;
        }
        for (String artistNo : artistNos) {
            this.updateArtist2(artistNo);
        }
    }


    private void updateArtist2(String artistNo) {
        if (StrUtil.isEmpty(artistNo)) {
            return;
        }
        List<ProductInfo> prdList = productInfoService.list(new QueryWrapper<ProductInfo>()
                .eq("biz_value4", artistNo)
        );
        if (CollUtil.isEmpty(prdList)) {
            return;
        }
        Set<String> prdNos = new HashSet<String>();
        prdList.forEach(item -> {
            prdNos.add(item.getProductNo());
        });
        String prds = StrSplitUtils.list2string_prefix(prdNos);
        if (StrUtil.isEmpty(prds)) {
            return;
        }
        artistUpdateMapper.updateArtist(artistNo, prds);

    }


    @PostMapping("/updateRel")
    @ApiOperation(value = "引用商品信息修改", response = BaseResult.class)
    @StaffLogc(title = "引用商品信息修改", action = "引用商品信息修改", actionAdo = "商品信息")
    public BaseResult updateRel(@RequestBody ProductRelInfoUpdateParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ProductInfo product = productMgrService.updateRel(params, userInfo);
        productProducer.editPrd(product);
        return BaseResult.ok();
    }

    @GetMapping("/addRel")
    @ApiOperation(value = "引用商品信息新增", response = Product.class)
    @StaffLogc(title = "引用商品信息新增", action = "引用商品信息新增", actionAdo = "商品信息")
    public BaseResult addRel(@RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ProductInfo entity = productMgrService.addRel(id, userInfo);
        productProducer.addPrd(entity);
        Product data = ProductCacheConvertUtils.convertProduct(entity, null, null, null, null);
        return BaseResult.ok(data);
    }

    @GetMapping("/delete")
    @ApiOperation(value = "商品信息删除", response = BaseResult.class)
    @StaffLogc(title = "商品信息删除", action = "商品信息删除", actionAdo = "商品信息")
    public BaseResult delete(@RequestParam("id") String id) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ProductInfo product = productMgrService.delete(id, userInfo);
        productInfoCacheService.removeProductByNoByCache(id);
        productDisProfitCacheService.removeProductDisProfit(id);
        productProducer.delPrd(product);
        return BaseResult.ok();
    }

    @PostMapping("/deleteBatch")
    @ApiOperation(value = "商品信息批量删除", response = BaseResult.class)
    @StaffLogc(title = "商品信息批量删除", action = "商品信息批量删除", actionAdo = "商品信息")
    public BaseResult deleteBatch(@RequestBody ProductInfoBatchParam params) {
        ValidatorUtils.validate(params);
        if (CollectionUtils.isEmpty(params.getIds())) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        params.getIds().forEach(id -> {
            ProductInfo product = productMgrService.delete(id, userInfo);
            productInfoCacheService.removeProductByNoByCache(id);
            productDisProfitCacheService.removeProductDisProfit(id);
            productProducer.delPrd(product);
        });
        return BaseResult.ok();
    }


    @GetMapping("/checkApply")
    @ApiOperation(value = "商品信息审核申请", response = BaseResult.class)
    @StaffLogc(title = "商品信息审核申请", action = "商品信息审核申请", actionAdo = "商品信息")
    public BaseResult checkApply(@RequestParam("id") String id) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        ProductInfo product = productInfoService.getById(id);
        if (product == null || EnabledEnum.DISABLED.getCode().equals(product.getRowsState())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_NULL);
        }
        if (YNEnum.YES.getCode().equals(product.getIsMarketable())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_UP_NotOp);
        }
        if (StrUtil.isEmpty(product.getState()) || ProductCheckStateEnum.PCS_Not.getCode().equals(product.getState())
                || ProductCheckStateEnum.PCS_Fail.getCode().equals(product.getState())) {
        } else {
            throw new BusinessException(BaseReturnEnum.PARAM_ERROR);
        }

        product.setState(ProductCheckStateEnum.PCS_Apply.getCode());
        product.addEditParam(userInfo);
        productInfoService.updateById(product);

        productInfoCacheService.removeProductByNoByCache(product.getProductNo());
        productDisProfitCacheService.removeProductDisProfit(product.getProductNo());
//		if(oldSkuNos.size()>0) {
//			productInfoCacheService.removeSku(oldSkuNos);
//		}

        return BaseResult.ok();
    }


    @GetMapping("/checkFail")
    @ApiOperation(value = "商品信息审核失败", response = BaseResult.class)
    @StaffLogc(title = "商品信息审核失败", action = "商品信息审核失败", actionAdo = "商品信息")
    public BaseResult checkFail(@RequestParam("id") String id) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        if (!"PTC".equals(userInfo.getCompanyNo())) {
            throw new BusinessException(BaseReturnEnum.NOT_AUTHC);
        }
        ProductInfo product = productInfoService.getById(id);
        if (product == null || EnabledEnum.DISABLED.getCode().equals(product.getRowsState())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_NULL);
        }
        if (YNEnum.YES.getCode().equals(product.getIsMarketable())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_UP_NotOp);
        }
//		if(StrUtil.isNotEmpty(product.getState()) && ProductCheckStateEnum.PCS_Apply.getCode().equals(product.getState())) {
//		}else {
//			throw new BusinessException(BaseReturnEnum.PARAM_ERROR);
//		}

        product.setState(ProductCheckStateEnum.PCS_Fail.getCode());
        product.addEditParam(userInfo);
        productInfoService.updateById(product);

        productInfoCacheService.removeProductByNoByCache(product.getProductNo());
        productDisProfitCacheService.removeProductDisProfit(product.getProductNo());
//		if(oldSkuNos.size()>0) {
//			productInfoCacheService.removeSku(oldSkuNos);
//		}

        return BaseResult.ok();
    }

    @GetMapping("/up")
    @ApiOperation(value = "商品信息审核通过并且上架", response = BaseResult.class)
    @StaffLogc(title = "商品信息审核通过并且上架", action = "商品信息审核通过并且上架", actionAdo = "商品信息")
    public BaseResult up(@RequestParam("id") String id) {
        ProductInfo product = productInfoService.getById(id);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        if (!"PTC".equals(userInfo.getCompanyNo())) {
            throw new BusinessException(BaseReturnEnum.NOT_AUTHC);
        }

        if (YNEnum.YES.getCode().equals(product.getIsMarketable())) {
            return BaseResult.ok();
        }

        product.setState(ProductCheckStateEnum.PCS_Success.getCode());
        product.setIsMarketable(YNEnum.YES.getCode());
        product.addEditParam(AuthContextUtils.getUser());
        productInfoService.updateById(product);
        productProducer.upPrd(product);
        return BaseResult.ok();
    }

    @PostMapping("/upBatch")
    @ApiOperation(value = "商品信息批量审核通过并且上架", response = BaseResult.class)
    @StaffLogc(title = "商品信息批量审核通过并且上架", action = "商品信息批量审核通过并且上架", actionAdo = "商品信息")
    public BaseResult upBatch(@RequestBody ProductInfoBatchParam params) {
        ValidatorUtils.validate(params);
        if (CollectionUtils.isEmpty(params.getIds())) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        if (!"PTC".equals(userInfo.getCompanyNo())) {
            throw new BusinessException(BaseReturnEnum.NOT_AUTHC);
        }
        List<ProductInfo> products = productInfoService.list(new QueryWrapper<ProductInfo>()
                .eq("rows_state", EnabledEnum.ENABLED.getCode())
                .in("product_no", params.getIds()));
        if (CollectionUtils.isEmpty(products)) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        List<ProductInfo> updateProducts = new ArrayList<ProductInfo>();
        products.forEach(model -> {
            if (!YNEnum.YES.getCode().equals(model.getIsMarketable())) {
                model.setState(ProductCheckStateEnum.PCS_Success.getCode());
                model.setIsMarketable(YNEnum.YES.getCode());
                model.addEditParam(userInfo);
                updateProducts.add(model);
            }
        });
        if (updateProducts.size() > 0) {
            productInfoService.updateBatchById(updateProducts);
            updateProducts.forEach(prd -> {
                productProducer.upPrd(prd);
            });
        }
        return BaseResult.ok();
    }


    @GetMapping("/down")
    @ApiOperation(value = "商品信息下架", response = BaseResult.class)
    @StaffLogc(title = "商品信息下架", action = "商品信息下架", actionAdo = "商品信息")
    public BaseResult down(@RequestParam("id") String id) {
        ProductInfo product = productInfoService.getById(id);
        if (product == null || EnabledEnum.DISABLED.getCode().equals(product.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if (YNEnum.NO.getCode().equals(product.getIsMarketable())) {
            return BaseResult.ok();
        }
        product.setIsMarketable(YNEnum.NO.getCode());
        product.setState(ProductCheckStateEnum.PCS_Not.getCode());
        product.addEditParam(AuthContextUtils.getUser());
        productInfoService.updateById(product);

        productInfoCacheService.removeProductByNoByCache(id);
        productDisProfitCacheService.removeProductDisProfit(id);
        productProducer.downPrd(product);
        return BaseResult.ok();
    }

    @PostMapping("/downBatch")
    @ApiOperation(value = "商品信息批量下架", response = BaseResult.class)
    @StaffLogc(title = "商品信息批量下架", action = "商品信息批量下架", actionAdo = "商品信息")
    public BaseResult downBatch(@RequestBody ProductInfoBatchParam params) {
        ValidatorUtils.validate(params);
        if (CollectionUtils.isEmpty(params.getIds())) {
            throw new BusinessException(BaseReturnEnum.PARAM_NULL);
        }
        List<ProductInfo> products = productInfoService.list(new QueryWrapper<ProductInfo>()
                .eq("rows_state", EnabledEnum.ENABLED.getCode())
                .in("product_no", params.getIds()));
        if (CollectionUtils.isEmpty(products)) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        List<ProductInfo> updateProducts = new ArrayList<ProductInfo>();
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        products.forEach(model -> {
            if (!YNEnum.NO.getCode().equals(model.getIsMarketable())) {
                model.setState(ProductCheckStateEnum.PCS_Not.getCode());
                model.setIsMarketable(YNEnum.NO.getCode());
                model.addEditParam(userInfo);
                updateProducts.add(model);
            }
        });

        if (updateProducts.size() > 0) {
            productInfoService.updateBatchById(updateProducts);
            updateProducts.forEach(item -> {
                productInfoCacheService.removeProductByNoByCache(item.getProductNo());
                productDisProfitCacheService.removeProductDisProfit(item.getProductNo());
                productProducer.downPrd(item);
            });

        }
        return BaseResult.ok();
    }

    @PostMapping("/querySpecification")
    @ApiOperation(value = "查询商品规格", response = BaseResult.class)
    public BaseResult querySpecification(@RequestBody SpecificationQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        IPage<SpecificationInfo> page = specificationInfoService.page(
                new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<SpecificationInfo>()
                        .eq("company_no", userInfo.getCompanyNo())
                        .like(CheckUtils.hasText(params.getName()), "name", params.getName())
        );

        IPage<SpecificationModel> data = page.convert(new Function<SpecificationInfo, SpecificationModel>() {
            @Override
            public SpecificationModel apply(SpecificationInfo entity) {
                SpecificationModel model = new SpecificationModel(entity.getId(), entity.getName(), entity.getOptions());
                return model;
            }
        });
        return BaseResult.ok(data);
    }


}
